package com.tuishan.myapplication.Views.Login;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.RegexUtils;
import com.blankj.utilcode.util.SPUtils;
import com.blankj.utilcode.util.StringUtils;
import com.google.gson.Gson;
import com.hjq.bar.OnTitleBarListener;
import com.hjq.bar.TitleBar;
import com.tuishan.myapplication.Base.BaseContest;
import com.tuishan.myapplication.Custom.LoadingView;
import com.tuishan.myapplication.Eum_Model.EyeEum;
import com.tuishan.myapplication.MainActivity;
import com.tuishan.myapplication.Model.RegisterModel;
import com.tuishan.myapplication.MyApplication;
import com.tuishan.myapplication.R;
import com.tuishan.myapplication.Servers.BaseCallback;
import com.tuishan.myapplication.Servers.OkHttpHelper;
import com.tuishan.myapplication.Servers.UrlRouter;
import com.tuishan.myapplication.Views.SetActivity;

import java.util.WeakHashMap;

import okhttp3.Request;
import okhttp3.Response;


public class RegisterActivity extends Activity implements View.OnClickListener, OnTitleBarListener {
    CheckBox Click_Boy, Click_Girl;
    ImageView eye_btn, eye_btn2;
    EditText login_ps_edt;
    EditText email_edit;
    EditText code_edit;
    EditText Re_nickname_edit;
    EditText M_PassWord_edit;
    EditText School_edit;
    EyeEum eyeEum = EyeEum.Close;
    EyeEum eyeEum2 = EyeEum.Close;
    Button code_send_btn;
    Button login_btn;
    private static long TOTAL_TIME = 60000;
    private final static long ONECE_TIME = 1000;
    Context mContext;
    TitleBar titleBar;
    LoadingView Loading;
    MyApplication myApp;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);
        mContext = this;
        myApp=(MyApplication)getApplication();
        ViewInit();
        EyeSet(eyeEum);
        EyeSet2(eyeEum2);
        Loading = new LoadingView(this);
    }

    private void ViewInit() {
        Click_Boy = findViewById(R.id.Click_Boy);
        Click_Girl = findViewById(R.id.Click_Girl);
        Click_Boy.setOnClickListener(this);
        Click_Girl.setOnClickListener(this);
        eye_btn = findViewById(R.id.eye_btn);
        eye_btn2 = findViewById(R.id.eye_btn2);
        eye_btn.setOnClickListener(this);
        eye_btn2.setOnClickListener(this);

        login_ps_edt = findViewById(R.id.login_ps_edt);
        code_send_btn = findViewById(R.id.code_send_btn);
        code_send_btn.setOnClickListener(this);
        login_btn = findViewById(R.id.login_btn);
        login_btn.setOnClickListener(this);
        email_edit = findViewById(R.id.email_edit);
        code_edit = findViewById(R.id.code_edit);
        Re_nickname_edit = findViewById(R.id.Re_nickname_edit);
        M_PassWord_edit = findViewById(R.id.M_PassWord_edit);
        School_edit = findViewById(R.id.School_edit);
        titleBar = findViewById(R.id.titleBar);
        titleBar.setOnTitleBarListener(this);
    }

    /**
     * 时间定时器
     */
    private CountDownTimer countDownTimer = new CountDownTimer(TOTAL_TIME, ONECE_TIME) {
        @Override
        public void onTick(long millisUntilFinished) {
            String value = String.valueOf((int) (millisUntilFinished / 1000));
            code_send_btn.setText(value);
        }

        @Override
        public void onFinish() {
            code_send_btn.setText(getResources().getString(R.string.phone_code));
            code_send_btn.setEnabled(true);
        }
    };

    /**
     * 关闭或者显示密码
     *
     * @param arg1 开关类型
     */
    private void EyeSet(EyeEum arg1) {
        switch (arg1) {
            case Open:
                eye_btn.setImageDrawable(getResources().getDrawable(R.drawable.visible_icon));
                login_ps_edt.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
                login_ps_edt.setSelection(login_ps_edt.getText().length());
                eyeEum = EyeEum.Close;
                break;
            case Close:
                eye_btn.setImageDrawable(getResources().getDrawable(R.drawable.invisible));
                login_ps_edt.setTransformationMethod(PasswordTransformationMethod.getInstance());
                login_ps_edt.setSelection(login_ps_edt.getText().length());
                eyeEum = EyeEum.Open;
                break;
        }
    }

    /**
     * 关闭或者显示密码
     *
     * @param arg1 开关类型
     */
    private void EyeSet2(EyeEum arg1) {
        switch (arg1) {
            case Open:
                eye_btn2.setImageDrawable(getResources().getDrawable(R.drawable.visible_icon));
                M_PassWord_edit.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
                M_PassWord_edit.setSelection(M_PassWord_edit.getText().length());
                eyeEum2 = EyeEum.Close;
                break;
            case Close:
                eye_btn2.setImageDrawable(getResources().getDrawable(R.drawable.invisible));
                M_PassWord_edit.setTransformationMethod(PasswordTransformationMethod.getInstance());
                M_PassWord_edit.setSelection(M_PassWord_edit.getText().length());
                eyeEum2 = EyeEum.Open;
                break;
        }
    }


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.Click_Boy:
                if (Click_Boy.isChecked()) {
                    Click_Girl.setChecked(false);
                }

                break;
            case R.id.Click_Girl:
                if (Click_Girl.isChecked()) {
                    Click_Boy.setChecked(false);
                }
                break;
            case R.id.eye_btn:
                EyeSet(eyeEum);
                break;
            case R.id.eye_btn2:
                EyeSet2(eyeEum2);
                break;
            case R.id.code_send_btn:
                if (!RegexUtils.isEmail(email_edit.getText().toString().trim())) {
                    Toast.makeText(this, "请确认账号输入是否正确", Toast.LENGTH_SHORT).show();
                    return;
                }
                code_send_btn.setEnabled(false);
                countDownTimer.start();
                SendCode(email_edit.getText().toString().trim());
                break;
            case R.id.login_btn:
                RegisterBtn(email_edit.getText().toString().trim(), login_ps_edt.getText().toString().trim(),
                        code_edit.getText().toString().trim(), Re_nickname_edit.getText().toString().trim()
                        , M_PassWord_edit.getText().toString().trim(), School_edit.getText().toString().trim());
                break;
        }
    }

    /**
     * 用户注册
     */
    private void RegisterBtn(String email, String Password, String Code, String nickName, String moneyPwd, String school) {
        if (!RegexUtils.isEmail(email)) {
            Toast.makeText(this, "请确认账号输入是否正确", Toast.LENGTH_SHORT).show();
            return;
        }
        if (StringUtils.isEmpty(Password)) {
            Toast.makeText(this, "请确认密码输入是否正确", Toast.LENGTH_SHORT).show();
            return;
        }
        if (StringUtils.isEmpty(Code)) {
            Toast.makeText(this, "请确认验证码输入是否正确", Toast.LENGTH_SHORT).show();
            return;
        }
        if (StringUtils.isEmpty(nickName)) {
            Toast.makeText(this, "请确认昵称输入是否正确", Toast.LENGTH_SHORT).show();
            return;
        }
        if (StringUtils.isEmpty(moneyPwd)) {
            Toast.makeText(this, "请确认资金密码输入是否正确", Toast.LENGTH_SHORT).show();
            return;
        }
        if (StringUtils.isEmpty(school)) {
            Toast.makeText(this, "请确认学校输入是否正确", Toast.LENGTH_SHORT).show();
            return;
        }
        if (!(Click_Boy.isChecked() || Click_Girl.isChecked())) {
            Toast.makeText(this, "请选择性别", Toast.LENGTH_SHORT).show();
            return;
        }
        Loading.show();
        WeakHashMap<String, Object> objectMap = new WeakHashMap<>();
        objectMap.put("userType", 1);
        objectMap.put("email", email);
        objectMap.put("loginPass", Password);
        objectMap.put("emailCode", Code);
        objectMap.put("nickName", nickName);
        objectMap.put("moneyPwd", moneyPwd);
        objectMap.put("school", school);
        objectMap.put("sex", Click_Boy.isChecked() ? 1 : 2);
        OkHttpHelper mHttpHelper = OkHttpHelper.getInstance();
        mHttpHelper.post(UrlRouter.RegisterUrl, RegisterModel.class, objectMap, new BaseCallback<RegisterModel>() {
            @Override
            public void onFailure(Request request, Exception e) {
                Loading.dismiss();
            }

            @Override
            public void onSuccess(Response response, RegisterModel registerModel) {
                Loading.dismiss();
                Toast.makeText(mContext, "注册成功", Toast.LENGTH_SHORT).show();
                SPUtils.getInstance().put(BaseContest.UserToken, registerModel.getToken());
                myApp.setLogin(true);
                finish();
                Intent intent = new Intent(mContext, MainActivity.class);
                startActivity(intent);
            }
            @Override
            public void onFalse(Response response, String err_msg) {
                Loading.dismiss();
                Toast.makeText(mContext, err_msg, Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onError(Response response, int errorCode, Exception e) {
                Loading.dismiss();
            }
        });
    }


    @Override
    public void onLeftClick(View v) {
        Intent intents = new Intent(mContext, SetActivity.class);
        startActivity(intents);
    }

    @Override
    public void onTitleClick(View v) {

    }

    @Override
    public void onRightClick(View v) {
        finish();
        Intent intent = new Intent(this, LoginActivity.class);
        startActivity(intent);
    }

    /**
     * 发送验证码
     */
    private void SendCode(String email) {
        Loading.show();
        WeakHashMap<String, Object> objectMap = new WeakHashMap<>();
        objectMap.put("email", email);
        objectMap.put("typeCode", 1);
        OkHttpHelper mHttpHelper = OkHttpHelper.getInstance();
        mHttpHelper.post(UrlRouter.SendEmail, String.class, objectMap, new BaseCallback() {
            @Override
            public void onFailure(Request request, Exception e) {
                Loading.dismiss();
            }

            @Override
            public void onSuccess(Response response, Object o) {
                Toast.makeText(mContext, "验证码发送成功", Toast.LENGTH_SHORT).show();
                Loading.dismiss();
            }

            @Override
            public void onFalse(Response response, String err_msg) {
                Toast.makeText(mContext, "接口失败", Toast.LENGTH_SHORT).show();
                Loading.dismiss();
            }

            @Override
            public void onError(Response response, int errorCode, Exception e) {
                Toast.makeText(mContext, "验证码发送失败", Toast.LENGTH_SHORT).show();
                Loading.dismiss();
            }
        });
    }
}
